package com.mouse.hxsj.view;

import com.mouse.hxsj.constants.SystemParams;
import com.mouse.hxsj.dao.GameAreaMapper;
import com.mouse.hxsj.dao.QqAccountMapper;
import com.mouse.hxsj.dao.QqRoleMapper;
import com.mouse.hxsj.entity.common.Point;
import com.mouse.hxsj.entity.enums.RoleEnum;
import com.mouse.hxsj.entity.po.GameArea;
import com.mouse.hxsj.entity.po.QqAccount;
import com.mouse.hxsj.entity.po.QqRole;
import com.mouse.hxsj.entity.po.mr.MrQqRole;
import com.mouse.hxsj.service.LoginService;
import com.mouse.hxsj.util.JsonUtil;
import com.mouse.hxsj.util.ViewGet;
import com.mouse.hxsj.util.ViewSet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Vector;

@Slf4j
@Component
public class RoleIFrm extends JInternalFrame {
    private JTextField textField_account;
    private JTextField textField_description;
    private JTable table;
    private JTextField textField_num;
    private JTextField textField_desc1;
    private JComboBox<RoleEnum> comboBox_role;
    private JComboBox<QqAccount> comboBox_account;
    private JComboBox<GameArea> comboBox_area;
    private JButton button_delete;
    private JButton button_login;
    private JPanel panel_save;

    @Autowired
    private QqRoleMapper qqRoleMapper;
    @Autowired
    private QqAccountMapper qqAccountMapper;
    @Autowired
    private GameAreaMapper gameAreaMapper;
    @Autowired
    private LoginService loginService;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    RoleIFrm frame = new RoleIFrm();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public RoleIFrm() {
        setClosable(true);
        setIconifiable(true);
        setTitle("游戏角色");
        setBounds(20, 20, 700, 500);

        JPanel panel_search = new JPanel();
        panel_search.setBorder(new TitledBorder(null, "搜索条件", TitledBorder.LEADING, TitledBorder.TOP, null, null));

        JScrollPane scrollPane = new JScrollPane();

        panel_save = new JPanel();
        panel_save.setBorder(new TitledBorder(null, "新增", TitledBorder.LEADING, TitledBorder.TOP, null, null));
        GroupLayout groupLayout = new GroupLayout(getContentPane());
        groupLayout.setHorizontalGroup(
        	groupLayout.createParallelGroup(Alignment.LEADING)
        		.addGroup(groupLayout.createSequentialGroup()
        			.addGap(29)
        			.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
        				.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 610, Short.MAX_VALUE)
        				.addComponent(panel_save, GroupLayout.PREFERRED_SIZE, 611, GroupLayout.PREFERRED_SIZE)
        				.addComponent(panel_search, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        			.addContainerGap())
        );
        groupLayout.setVerticalGroup(
        	groupLayout.createParallelGroup(Alignment.LEADING)
        		.addGroup(groupLayout.createSequentialGroup()
        			.addGap(20)
        			.addComponent(panel_search, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 156, GroupLayout.PREFERRED_SIZE)
        			.addPreferredGap(ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
        			.addComponent(panel_save, GroupLayout.PREFERRED_SIZE, 168, GroupLayout.PREFERRED_SIZE)
        			.addGap(26))
        );

        JLabel label_1 = new JLabel("编号");

        textField_num = new JTextField();
        textField_num.setEditable(false);
        textField_num.setColumns(10);

        JLabel label_2 = new JLabel("账号");

        JLabel label_3 = new JLabel("区");

        JLabel label_4 = new JLabel("角色");

        comboBox_role = new JComboBox();
        comboBox_role.setModel(new DefaultComboBoxModel(RoleEnum.values()));

        comboBox_account = new JComboBox();
        comboBox_area = new JComboBox();

        JLabel label_5 = new JLabel("备注");

        textField_desc1 = new JTextField();
        textField_desc1.setColumns(10);

        JButton button = new JButton("保存");
        button.addActionListener(e -> save());

        button_delete = new JButton("删除");
        button_delete.addActionListener(e -> delete());

        button_login = new JButton("登录");
        button_login.addActionListener(e -> login());
        GroupLayout gl_panel_1 = new GroupLayout(panel_save);
        gl_panel_1.setHorizontalGroup(
                gl_panel_1.createParallelGroup(Alignment.LEADING)
                        .addGroup(gl_panel_1.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
                                        .addGroup(gl_panel_1.createSequentialGroup()
                                                .addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
                                                        .addComponent(label_1)
                                                        .addComponent(label_4, GroupLayout.PREFERRED_SIZE, 36, GroupLayout.PREFERRED_SIZE))
                                                .addPreferredGap(ComponentPlacement.RELATED)
                                                .addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
                                                        .addComponent(comboBox_role, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                        .addComponent(textField_num, GroupLayout.PREFERRED_SIZE, 104, GroupLayout.PREFERRED_SIZE))
                                                .addGap(27)
                                                .addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING, false)
                                                        .addGroup(gl_panel_1.createSequentialGroup()
                                                                .addComponent(label_2, GroupLayout.PREFERRED_SIZE, 36, GroupLayout.PREFERRED_SIZE)
                                                                .addPreferredGap(ComponentPlacement.RELATED)
                                                                .addComponent(comboBox_account, GroupLayout.PREFERRED_SIZE, 104, GroupLayout.PREFERRED_SIZE)
                                                                .addGap(39)
                                                                .addComponent(label_3, GroupLayout.PREFERRED_SIZE, 36, GroupLayout.PREFERRED_SIZE)
                                                                .addPreferredGap(ComponentPlacement.RELATED)
                                                                .addComponent(comboBox_area, GroupLayout.PREFERRED_SIZE, 104, GroupLayout.PREFERRED_SIZE))
                                                        .addGroup(gl_panel_1.createSequentialGroup()
                                                                .addComponent(label_5, GroupLayout.PREFERRED_SIZE, 36, GroupLayout.PREFERRED_SIZE)
                                                                .addPreferredGap(ComponentPlacement.RELATED)
                                                                .addComponent(textField_desc1))))
                                        .addGroup(gl_panel_1.createSequentialGroup()
                                                .addComponent(button, GroupLayout.PREFERRED_SIZE, 67, GroupLayout.PREFERRED_SIZE)
                                                .addGap(28)
                                                .addComponent(button_delete, GroupLayout.PREFERRED_SIZE, 67, GroupLayout.PREFERRED_SIZE)
                                                .addGap(26)
                                                .addComponent(button_login, GroupLayout.PREFERRED_SIZE, 68, GroupLayout.PREFERRED_SIZE)))
                                .addContainerGap(91, Short.MAX_VALUE))
        );
        gl_panel_1.setVerticalGroup(
                gl_panel_1.createParallelGroup(Alignment.LEADING)
                        .addGroup(gl_panel_1.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
                                        .addComponent(label_1)
                                        .addComponent(textField_num, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                        .addComponent(label_2)
                                        .addComponent(label_3)
                                        .addComponent(comboBox_account, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                        .addComponent(comboBox_area, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                                .addGap(30)
                                .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
                                        .addComponent(label_4)
                                        .addComponent(label_5)
                                        .addComponent(textField_desc1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                        .addComponent(comboBox_role, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
                                .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
                                        .addComponent(button)
                                        .addComponent(button_delete)
                                        .addComponent(button_login))
                                .addContainerGap())
        );
        panel_save.setLayout(gl_panel_1);

        table = new JTable();
        table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent met) {
                tableSelected(met);
            }
        });
        table.setModel(new DefaultTableModel(
                new Object[][]{
                },
                new String[]{
                        "编号", "账号", "区", "角色", "备注"
                }
        ));
        scrollPane.setViewportView(table);

        JLabel lblNewLabel = new JLabel("账号");

        textField_account = new JTextField();
        textField_account.setColumns(10);

        JLabel label = new JLabel("备注");

        textField_description = new JTextField();
        textField_description.setColumns(10);

        JButton btnNewButton = new JButton("搜索");
        btnNewButton.addActionListener(arg0 -> initTable());
        JButton btnNewButton_1 = new JButton("新增");
        btnNewButton_1.addActionListener(e -> addRole());

        JButton button_clear = new JButton("清空");
        button_clear.addActionListener(e -> {
            textField_account.setText("");
            textField_description.setText("");
            initTable();
        });
        GroupLayout gl_panel = new GroupLayout(panel_search);
        gl_panel.setHorizontalGroup(
                gl_panel.createParallelGroup(Alignment.LEADING)
                        .addGroup(gl_panel.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(lblNewLabel)
                                .addPreferredGap(ComponentPlacement.RELATED)
                                .addComponent(textField_account, GroupLayout.PREFERRED_SIZE, 104, GroupLayout.PREFERRED_SIZE)
                                .addGap(27)
                                .addComponent(label, GroupLayout.PREFERRED_SIZE, 36, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(ComponentPlacement.RELATED)
                                .addComponent(textField_description, GroupLayout.PREFERRED_SIZE, 104, GroupLayout.PREFERRED_SIZE)
                                .addGap(18)
                                .addComponent(btnNewButton)
                                .addGap(26)
                                .addComponent(button_clear)
                                .addPreferredGap(ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
                                .addComponent(btnNewButton_1)
                                .addGap(38))
        );
        gl_panel.setVerticalGroup(
                gl_panel.createParallelGroup(Alignment.LEADING)
                        .addGroup(gl_panel.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
                                        .addComponent(lblNewLabel)
                                        .addComponent(textField_account, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                        .addComponent(label)
                                        .addComponent(textField_description, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                        .addComponent(btnNewButton)
                                        .addComponent(btnNewButton_1)
                                        .addComponent(button_clear))
                                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        panel_search.setLayout(gl_panel);
        getContentPane().setLayout(groupLayout);
    }

    private void login() {
        Integer id = ViewGet.textField(textField_num, Integer.class);
        QqRole qqRole = qqRoleMapper.selectById(id);
        QqAccount qqAccount = qqAccountMapper.selectById(qqRole.getQqAccountId());
        GameArea gameArea = gameAreaMapper.selectById(qqRole.getGameAreaId());

        log.info(SystemParams.sourcePath);
        log.info(SystemParams.exePath);
        log.info(qqAccount.getUserName());
        log.info(qqAccount.getPassword());
        log.info(JsonUtil.toJson(Point.init(gameArea.getAreaPoint())));
        log.info(JsonUtil.toJson(Point.init(gameArea.getZonePoint())));
        log.info(JsonUtil.toJson(RoleEnum.getByNum(qqRole.getRoleNum())));
//        button_login.setEnabled(false);
        new Thread(() -> {
            try {
                loginService.login(qqAccount.getUserName(), qqAccount.getPassword(), Point.init(gameArea.getAreaPoint()),
                        Point.init(gameArea.getZonePoint()), RoleEnum.getByNum(qqRole.getRoleNum()));
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
//            button_login.setEnabled(true);
        }).start();
    }

    private void delete() {
        Integer id = ViewGet.textField(textField_num, Integer.class);
        int result = JOptionPane.showConfirmDialog(null, "是否删除id为" + id + "数据");
        if (result != 0) return;
        if (id != null) qqRoleMapper.deleteById(id);
        initTable();
    }

    private void save() {
        QqRole qqRole = new QqRole();
        Integer id = ViewGet.textField(textField_num, Integer.class);
        qqRole.setId(id);
        qqRole.setQqAccountId(ViewGet.comboBox(comboBox_account, "id", Integer.class));
        qqRole.setGameAreaId(ViewGet.comboBox(comboBox_area, "id", Integer.class));
        qqRole.setRoleNum(ViewGet.comboBox(comboBox_role, "roleNum", Integer.class));
        qqRole.setDescription(ViewGet.textField(textField_desc1));
        if (id == null) {
            qqRoleMapper.insert(qqRole);
        } else {
            qqRoleMapper.updateById(qqRole);
        }
        initTable();
    }

    private void addRole() {
        clear();
        addViewFlag(true);
    }

    public void initFrm() {
        initTable();
        comboBox_account.setModel(new DefaultComboBoxModel<>());
        comboBox_account.setModel(new DefaultComboBoxModel<>());
        qqAccountMapper.selectList(null).forEach(qqAccount -> comboBox_account.addItem(qqAccount));
        gameAreaMapper.selectList(null).forEach(gameArea -> comboBox_area.addItem(gameArea));
        addViewFlag(true);
    }

    private void tableSelected(MouseEvent met) {
        addViewFlag(false);

        int row = table.getSelectedRow();
        Integer roleId = (Integer) table.getValueAt(row, 0);
        QqRole qqRole = qqRoleMapper.selectById(roleId);
        ViewSet.textField(textField_num, roleId);
        ViewSet.textField(textField_desc1, qqRole.getDescription());
        ViewSet.comboBox(comboBox_role, table.getValueAt(row, 3), "roleNum");
        ViewSet.comboBox(comboBox_account, qqRole.getQqAccountId(), "id");
        ViewSet.comboBox(comboBox_area, qqRole.getGameAreaId(), "id");
    }

    public void initTable() {
        addViewFlag(true);
        clear();
        if (qqRoleMapper == null) return;
        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
        tableModel.setRowCount(0);
        List<MrQqRole> list = qqRoleMapper.findAll(
                "%"+ViewGet.textField(textField_account)+"%",
                "%"+ViewGet.textField(textField_description)+"%");
        for (MrQqRole role : list) {
            Vector vector = new Vector();
            vector.add(role.getId());
            vector.add(role.getQqAccountName());
            vector.add(role.getGameAreaName());
            vector.add(role.getRoleNum());
            vector.add(role.getDescription());
            tableModel.addRow(vector);
        }
    }

    private void clear() {
        ViewSet.textField(textField_num, "");
        ViewSet.textField(textField_desc1, "");
        ViewSet.comboBox(comboBox_role, 0);
        ViewSet.comboBox(comboBox_account, 0);
        ViewSet.comboBox(comboBox_area, 0);
    }

    private void addViewFlag(boolean flag) {
        if (flag) {
            button_delete.setVisible(false);
            button_login.setVisible(false);
            panel_save.setBorder(new TitledBorder(null, "新增", TitledBorder.LEADING, TitledBorder.TOP, null, null));
        } else {
            button_delete.setVisible(true);
            button_login.setVisible(true);
            panel_save.setBorder(new TitledBorder(null, "编辑", TitledBorder.LEADING, TitledBorder.TOP, null, null));
        }
    }
}
